package org.im.service.websocket.server;

import java.util.Collection;

import javax.websocket.EndpointConfig;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

import org.im.service.message.bean.ActionType;
import org.im.service.message.bean.MessageUserType;
import org.im.service.message.exp.MessageException;
import org.im.service.message.webmsg.UserInfoMessage;
import org.im.service.websocket.server.pool.WebsocketSessionPool;

import com.alibaba.fastjson.JSON;

@ServerEndpoint(value = "/websocket")
public class WebsocketPipelineAction {
	
	@OnOpen
	public void open(Session session, EndpointConfig config) {
		Collection<String> ids = WebsocketSessionPool.getAllSessionIds();

		//新会话
		String sessionId = session.getId();
		WebsocketMessageContext.createWebsocketPipeline(session);
		UserInfoMessage userInfo = new UserInfoMessage();
		userInfo.setFromId("100");
		userInfo.setActionType(ActionType.NEW_USER.getType());
		userInfo.setFromUserType(MessageUserType.SYSTEM.getType());
		userInfo.setSessionId(sessionId);
		userInfo.setOtherSessionIds(ids);
		try {
			WebsocketMessageContext.sendMessage(session, sessionId, JSON.toJSONString(userInfo));
		} catch (MessageException e1) {
			e1.printStackTrace();
		}
		
		//发送系统消息：向好友发送登录消息
		try {

			userInfo = new UserInfoMessage();
			userInfo.setFromId(sessionId);
			userInfo.setActionType(ActionType.NEW_USER.getType());
			userInfo.setFromUserType(MessageUserType.NORMAL_USER.getType());
			userInfo.setSessionId(sessionId);
			
			WebsocketMessageContext.sendMessageToSession(session, ids, JSON.toJSONString(userInfo));
		} catch (Exception e) {
		}
	}

	@OnMessage
	public void inMessage(Session session, String message) {
		//接收到客户端消息，发送给指定的session
		try {
			WebsocketMessageContext.sendMessageToSession(session, message);
		} catch (MessageException e) {
			e.printStackTrace();
		}
	}

	@OnClose
	public void end(Session session) {
		
		try {
			Collection<String> toIds = WebsocketSessionPool.getAllSessionIds();
			UserInfoMessage userInfo = new UserInfoMessage();
			userInfo.setFromId(session.getId());
			userInfo.setFromUserType(MessageUserType.NORMAL_USER.getType());
			userInfo.setActionType(ActionType.USER_LEAVE.getType());
			userInfo.setSessionId(session.getId());
			toIds.remove(session.getId());
			WebsocketMessageContext.sendMessageToSession(session, toIds, JSON.toJSONString(userInfo));
		} catch (Exception e) {
			e.printStackTrace();
		}

		//会话结束
		WebsocketMessageContext.distroyWebsocketPipeline(session);
	}
}
